package com.leyou.page.service.impl;

import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpuDTO;
import com.leyou.page.service.IPageService;
import com.leyou.test.enums.ExceptionEnum;
import com.leyou.test.exceptions.LyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PageServiceImpl implements IPageService {

    @Autowired
    private ItemClient itemClient;

    @Value("${ly.static.itemDir}")
    private String itemDir;

    @Value("${ly.static.itemTemplate}")
    private String itemTemplate;

    @Autowired
    private SpringTemplateEngine templateEngine;

    /**
     * 查询商品详情页面数据
     * @return
     */
    @Override
    public Map<String, Object> toItemPage(Long id) {
        HashMap<String, Object> map = new HashMap<>();
        //1.查询spu
        SpuDTO spuDTO = itemClient.querySpuById(id);
        //2.查询分类集合
        List<CategoryDTO> categoryDTOS = itemClient.queryCategoryByIds(spuDTO.getCategoryIds());
        //3.查询品牌
        BrandDTO brandDTO = itemClient.queryBrandById(spuDTO.getBrandId());
        //4.查询规格
        List<SpecGroupDTO> specs = itemClient.querySpecsByCid(spuDTO.getCid3());
        //5.封装数据
        map.put("spuName", spuDTO.getName());
        map.put("subTitle", spuDTO.getSubTitle());
        map.put("detail", spuDTO.getSpuDetail());
        map.put("skus", spuDTO.getSkus());
        map.put("categories", categoryDTOS);
        map.put("brand", brandDTO);
        map.put("specs", specs);
        System.out.println(map);
        System.out.println("1111");
        return map;
    }

    /**
     * 创建静态化页面
     * @param id
     */
    public void createItemHtml(Long id) {
        //准备数据模型
        Context context = new Context();
        //将数据加载到模型中
        context.setVariables(toItemPage(id));
        //准备文件路径
        File dir = new File(itemDir);
        if (!dir.exists()) {
            try {
                dir.mkdirs();
            } catch (Exception e) {
                //创建目录路径失败
                throw new LyException(ExceptionEnum.DIRECTORY_WRITER_ERROR);
            }
        }
        File file = new File(dir, id + ".html");
        //输出流保存到硬盘
        try (PrintWriter printWriter = new PrintWriter(file, "utf-8")) {
            templateEngine.process(itemTemplate, context, printWriter);
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.DIRECTORY_WRITER_ERROR);
        }
    }

    /**
     * 删除静态化页面
     * @param id
     */
    @Override
    public void deleteItemHtml(Long id) {
        File file = new File(itemDir, id + ".html");
        if (file.exists()) {
            boolean delete = file.delete();
            //如果删除失败,抛出异常
            if (!delete) {
                throw new LyException(ExceptionEnum.DELETE_OPERATION_FAIL);
            }
        }
    }
}
